package net.stogi.dsper.ui.client.module.dataobject;

import java.util.Map.Entry;

import net.stogi.common.gwt.dispatch.client.core.ActionManager;
import net.stogi.common.gwt.frame.client.core.EventBus;
import net.stogi.common.gwt.frame.client.mvp.AbstractPresenter;
import net.stogi.common.mvp.core.model.KeyValues;
import net.stogi.dsper.api.dto.DataObjectDto;

class DataObjectPreviewPresenter extends AbstractPresenter {

	private DataObjectPreviewView dataObjectPreviewView;

	public DataObjectPreviewPresenter(DataObjectPreviewView dataObjectPreviewView, ActionManager actionManager, EventBus eventBus) {
		super(actionManager, eventBus);
		this.dataObjectPreviewView = dataObjectPreviewView;
		initBehavior();
		initHandlers();
	}

	@Override
	protected void initBehavior() {}

	@Override
	protected void initHandlers() {
		eventBus.addHandler(CloseDataObjectPreviewEvent.TYPE, new CloseDataObjectPreviewHandler() {

			@Override
			public void onCloseDataObjectPreview(CloseDataObjectPreviewEvent event) {
				dataObjectPreviewView.disappear();
			}
		});
		eventBus.addHandler(OpenDataObjectPreviewEvent.TYPE, new OpenDataObjectPreviewHandler() {

			@Override
			public void onOpenDataObjectPreview(OpenDataObjectPreviewEvent event) {
				dataObjectPreviewView.appear();
				internalDisplayDataObject(event.getDataObject());
			}
		});
	}

	private void internalDisplayDataObject(DataObjectDto dataObject) {
		KeyValues<String> model = new KeyValues<String>(dataObject.getDataValues().get("title"));
		model.setValue("dataSourceName", dataObject.getDataSourceName());
		model.setValue("userProfileName", dataObject.getUserProfileName());
		for (Entry<String, String> entry : dataObject.getDataValues().entrySet()) {
			model.setValue(entry.getKey(), entry.getValue());
		}
		dataObjectPreviewView.displayDataObject(model);
	}
}
